/*

This file is part of Rooms3D.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
Rooms3D is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
Rooms3D is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with Rooms3D; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
*/

import java.awt.Dimension;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 * @author rickp
 * 
 */
public class WebStart implements Runnable
{
	private static Logger logger = Logger.getLogger(WebStart.class.getName());
	final private static String RESOURCE_URL_PROPERTY = "com.datasentinel.rooms.resource";
	private String appToLaunch = "com.datasentinel.rooms.ui.sh3d.Main";
	private String launchArgs[];
	
	public WebStart(String args[])
	{
		if(args.length > 0)
		{
			appToLaunch = args[0];
			launchArgs = new String[args.length-1];
			System.arraycopy(args, 1, launchArgs, 0, args.length-1);
			logger.config("will launch "+appToLaunch+" with arguments:"+Arrays.toString(launchArgs));
		}
	}

	public void run()
	{
		try
		{
			String resourceURL = System.getProperty(RESOURCE_URL_PROPERTY);
			if (resourceURL instanceof String)
			{
				if (-1 == resourceURL.toLowerCase().indexOf(".jar")
						&& !resourceURL.endsWith("/"))
				{
					logger.warning("system property [" + RESOURCE_URL_PROPERTY
							+ "=" + resourceURL
							+ "] does not end in .jar or end in /");
					resourceURL += "/";
				}
				else
				{
					logger.config("system property [" + RESOURCE_URL_PROPERTY
							+ "=" + resourceURL + "]");
				}
			}
			else
			{
				throw new IllegalStateException("required system property ["
						+ RESOURCE_URL_PROPERTY + "] has not been set");
			}
			URL cpElement = new URL(resourceURL);
			URLClassLoader systemCL = (URLClassLoader)WebStart.class
					.getClassLoader();
			Method addURLmethod = URLClassLoader.class.getDeclaredMethod(
					"addURL", new Class[] { URL.class });
			addURLmethod.setAccessible(true);
			addURLmethod.invoke(systemCL, cpElement);
			Method classMainMethod = Class.forName(appToLaunch)
					.getDeclaredMethod("main", String[].class);
			classMainMethod.invoke(null, new Object[]{launchArgs});
		}
		catch (final Exception e)
		{
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			sw.write("Sorry, an error occurred.  Details below:\n\n");
			e.printStackTrace(pw);
			logger.log(Level.SEVERE,
					"Sorry, an error occurred.  Details below", e);
			JTextArea jta = new JTextArea(sw.toString());
			JScrollPane jsp = new JScrollPane(jta);
			jsp.setPreferredSize(new Dimension(800, 600));
			JOptionPane.showMessageDialog(null, jsp, "Severe Error",
					JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
	}

	public static void main(String[] args)
	{
		WebStart ws = new WebStart(args);
		SwingUtilities.invokeLater(ws);
	}
}
